package com.ruoyi.web.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.enums.AbnormalEnum;
import com.ruoyi.framework.web.exception.TadpoleException;
import com.ruoyi.web.domain.AppUser;
import com.ruoyi.web.domain.WithdrawalRecord;
import com.ruoyi.web.dto.ApplyWithdrawalDTO;
import com.ruoyi.web.dto.WithdrawalRecordDTO;
import com.ruoyi.web.dto.WithdrawalToExamineDTO;
import com.ruoyi.web.enums.WalletStatusEnums;
import com.ruoyi.web.mapper.WithdrawalRecordMapper;
import com.ruoyi.web.service.IAppUserService;
import com.ruoyi.web.service.IWithdrawalRecordService;
import com.ruoyi.web.vo.WithdrawalRecordVO;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 提现记录Controller
 *
 * @author ruoyi
 * @date 2023-01-05
 */
@RestController
@RequestMapping("/withdrawal")
@AllArgsConstructor
public class WithdrawalRecordController extends BaseController {
    private final IWithdrawalRecordService withdrawalRecordService;
    private final WithdrawalRecordMapper recordMapper;
    private final IAppUserService appUserService;

    @PostMapping("/apply")
    public R<String> create(@RequestBody ApplyWithdrawalDTO dto) {
        return withdrawalRecordService.create(dto);
    }

    /**
     * 查询提现记录列表
     */
    @GetMapping("/list")
    public TableDataInfo list() {
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            throw new TadpoleException(AbnormalEnum.MSG.OPTIONS_USER_NOT_FOUND);
        }
        startPage();
        List<WithdrawalRecord> list = withdrawalRecordService.selectWithdrawalRecordList(new WithdrawalRecord() {{
            setUserId(userId);
        }});
        TableDataInfo info = getDataTable(list);

        List<WithdrawalRecordVO> voList = new ArrayList<>();
        for (WithdrawalRecord record : list) {
            WithdrawalRecordVO vo = new WithdrawalRecordVO();
            BeanUtils.copyProperties(record, vo);
            vo.setState(WalletStatusEnums.Status.findName(vo.getState()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(record.getCreateTime());
            vo.setCreateTime(format);
            voList.add(vo);
        }
        return getDataTable(info, voList);
    }

    /**
     * 查询提现记录列表
     */
    @GetMapping("/page/list")
    public TableDataInfo pageList(WithdrawalRecord withdrawalRecord) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<WithdrawalRecord> records;
        if (loginUser.getUser().getRoles().get(0).getRoleId() == 3) {
            // 获取所有子集
            List<AppUser> userList = new ArrayList<>();
            appUserService.getAllChild(userList, loginUser.getUserId());
            List<Long> userIdList = userList.stream()
                    .map(AppUser::getId)
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(userIdList)) {
                return getDataTable(new ArrayList<>());
            }

            WithdrawalRecordDTO condition = new WithdrawalRecordDTO();
            condition.setUserIdList(userIdList);
            condition.setUserId(withdrawalRecord.getUserId());

            startPage();
            records = recordMapper.selectChildWithdrawalRecordList(condition);
        } else {
            startPage();
            records = withdrawalRecordService.selectWithdrawalRecordList(withdrawalRecord);
        }
        TableDataInfo info = getDataTable(records);

        List<WithdrawalRecordVO> voList = new ArrayList<>();
        for (WithdrawalRecord record : records) {
            WithdrawalRecordVO vo = new WithdrawalRecordVO();
            BeanUtils.copyProperties(record, vo);
            vo.setState(WalletStatusEnums.Status.findName(vo.getState()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(record.getCreateTime());
            vo.setCreateTime(format);
            voList.add(vo);
        }
        return getDataTable(info, voList);
    }

    @PostMapping("/examine")
    public R<String> toExamine(@RequestBody WithdrawalToExamineDTO dto) {
        return withdrawalRecordService.toExamine(dto);
    }

    /**
     * 通过
     *
     * @param id id
     * @return {@link R< Object>}
     * @since 2023/4/1 15:42
     */
    @PostMapping("/approve/{id}")
    public AjaxResult approve(@PathVariable("id") Long id) {
        withdrawalRecordService.approve(id);
        return success();
    }

    /**
     * 拒绝
     *
     * @param id id
     * @return {@link R< Object>}
     * @since 2023/4/1 15:42
     */
    @PostMapping("/reject/{id}")
    public AjaxResult reject(@PathVariable("id") Long id) {
        withdrawalRecordService.reject(id);
        return success();
    }

    /**
     * 导出提现记录列表
     */
    @PreAuthorize("@ss.hasPermi('web:record:export')")
    @Log(title = "提现记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WithdrawalRecord withdrawalRecord) {
        List<WithdrawalRecord> list = withdrawalRecordService.selectWithdrawalRecordList(withdrawalRecord);
        ExcelUtil<WithdrawalRecord> util = new ExcelUtil<WithdrawalRecord>(WithdrawalRecord.class);
        util.exportExcel(response, list, "提现记录数据");
    }

    /**
     * 获取提现记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('web:record:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(withdrawalRecordService.selectWithdrawalRecordById(id));
    }

    /**
     * 新增提现记录
     */
    @PreAuthorize("@ss.hasPermi('web:record:add')")
    @Log(title = "提现记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WithdrawalRecord withdrawalRecord) {
        return toAjax(withdrawalRecordService.insertWithdrawalRecord(withdrawalRecord));
    }

    /**
     * 修改提现记录
     */
    @PreAuthorize("@ss.hasPermi('web:record:edit')")
    @Log(title = "提现记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WithdrawalRecord withdrawalRecord) {
        return toAjax(withdrawalRecordService.updateWithdrawalRecord(withdrawalRecord));
    }

    /**
     * 删除提现记录
     */
    @PreAuthorize("@ss.hasPermi('web:record:remove')")
    @Log(title = "提现记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<String> remove(@PathVariable Long[] ids) {
        return withdrawalRecordService.refuse(ids[0], "拒绝");
    }


}
